<template>
  <template v-if="user">
    <van-cell icon="photo-o" title="头像" is-link center>
      <van-uploader v-model="fileList" :max-count="1" :after-read="afterRead" preview-size="60px">
        <img :src="imgSrc" style="width: 48px;height: 48px;border-radius: 50%" alt=""/>
      </van-uploader>
    </van-cell>
    <van-cell icon="contact" title="昵称" is-link to="/user/edit" :value="user.nickname"  @click="toEdit('nickname', '昵称', user.nickname)"/>
    <van-cell icon="user-o"  title="账号" :value="user.loginAccount"/>
    <van-cell icon="user-o"  title="密码" value="*********" is-link to="/user/resetPassword"/>
    <van-cell icon="diamond" title="性别" is-link :value="user.gender" @click="toEdit('gender', '性别', user.gender)"/>
    <van-cell icon="phone-o" title="电话" is-link to="/user/edit" :value="user.phone" @click="toEdit('phone', '电话', user.phone)"/>
    <van-cell icon="orders-o" title="个性签名" is-link to="/user/edit" :value="user.userInfo" @click="toEdit('userInfo', '个性签名', user.userInfo)"/>
  </template>
</template>

<script setup lang="ts">
import {useRouter} from "vue-router";
import {onMounted, ref} from "vue";
import myAxios from "../../api/myAxios";
import {Toast} from "vant";
import {getCurrentUser} from "../../services/user";

const user = ref();
const fileList = ref([])
const imgSrc = ref('')

const afterRead = async () => {
  let formData = new FormData();
  formData.append("file", fileList.value[0].file)
  const res = await myAxios.post("/file/upload", formData, {
    headers: {
      'Content-Type': 'multipart/form-data'
    }
  })
  if (res?.code === 0) {
    Toast("更新成功")
    imgSrc.value = res?.data
  } else {
    console.log(res)
    Toast("更新失败：" + res.data.message)
  }
  fileList.value = []
}

async function getUser() {
  let currentUser = await getCurrentUser();
  if (currentUser) {
    user.value = currentUser
    imgSrc.value = currentUser.avatarUrl
  } else {
    Toast("未登录")
    await router.replace("/user/login")
  }
}

onMounted(async () => {
  await getUser();
})

const router = useRouter();

const toUpdateAvatar = () => {
  router.push({
    path: '/file/upload',
  })
}

const toEdit = (editKey: string, editName: string, currentValue: string) => {
  router.push({
    path: '/user/edit',
    query: {
      editKey,
      editName,
      currentValue,
    }
  })
}
</script>

<style scoped>

</style>
